<template>
	<view class="container">
		
		<!-- 搜索栏 -->
		<view class="search-section">
			<view class="search-box">
				<text class="search-icon">🔍</text>
				<input 
					v-model="searchKeyword" 
					placeholder="搜索盘点单号"
					@input="onSearchInput"
					class="search-input"
				/>
				<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">✕</text>
			</view>
			<view class="header-actions">
				<view class="action-btn add-btn" @click="goAdd">
					<text class="btn-icon">+</text>
				</view>
			</view>
		</view>
		
		<!-- 盘点单卡片列表 -->
		<view class="inventory-list">
			<view 
				v-for="(item, index) in inventoryList" 
				:key="index" 
				class="inventory-card" 
				@click="viewDetail(item, index)"
			>
			<!-- 卡片内容 -->
			<view class="card-content">
					<view class="card-header">
						<text class="card-title">盘点单号</text>
						<text class="status-badge" :class="item.status === 'COMPLETED' ? 'completed' : 'pending'">
							{{ getStatusName(item.status) }}
						</text>
					</view>
					
					<view class="card-info">
						<view class="info-row">
							<text class="info-label">计划时间：</text>
							<text class="info-value">{{ formatDate(item.plannedDate) }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">备件仓库：</text>
							<text class="info-value">{{ getWarehouseName(item.warehouseCode) }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">盘点人员：</text>
							<text class="info-value">{{ item.inventoryUser || '-' }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="inventoryList.length === 0">
			<text class="empty-icon">📋</text>
			<text class="empty-text">暂无盘点单</text>
		</view>
	</view>
</template>

<script>
	import { listInventory, delInventory } from '@/api/inventory/inventory.js'
	
	export default {
		data() {
			return {
				searchKeyword: '',
				inventoryList: [],
				apiResponse: null,
				// 调试信息
				dataLength: 0,
				apiStatus: '加载中',
				firstData: '无',
				// 仓库映射
				warehouseMapping: {
					'WH001': '主仓库',
					'WH002': '备用仓库',
					'WH003': '临时仓库',
					'MAIN': '主仓库',
					'BACKUP': '备用仓库',
					'TEMP': '临时仓库'
				},
				// 状态映射
				statusMapping: {
					'PENDING': '待盘点',
					'IN_PROGRESS': '盘点中',
					'COMPLETED': '盘点完成',
					'CANCELLED': '已取消'
				}
			}
		},
		
		onLoad() {
			console.log('页面加载');
			// 延迟加载，确保页面完全渲染
			this.$nextTick(() => {
				this.loadData();
			});
		},

		onShow() {
			console.log('页面显示');
			// 每次显示都重新加载数据
			this.loadData();
		},
		
		methods: {
			// 加载数据
			async loadData() {
				try {
					console.log('开始加载盘点单数据...');
					const res = await listInventory({});
					console.log('API返回数据:', res);
					this.apiResponse = res;
					this.apiStatus = '已响应';
					
					if (res && res.rows && res.rows.length > 0) {
						const newData = res.rows.map((item, index) => ({
							id: item.id || index,
							sessionNo: item.sessionNo || '-',
							plannedDate: item.plannedDate,
							actualDate: item.actualDate,
							warehouseCode: item.warehouseCode,
							inventoryUser: item.inventoryUser || '-',
							status: item.status || 'PENDING',
							checkerId: item.checkerId,
							createdAt: item.createdAt,
							updatedAt: item.updatedAt
						}));
						
						console.log('处理后的数据:', newData);
						console.log('数据长度:', newData.length);
						
						// 使用Vue.set确保响应式更新
						this.$set(this, 'inventoryList', newData);
						console.log('设置后的数据:', this.inventoryList);
						console.log('设置后的长度:', this.inventoryList.length);
						
						// 更新调试信息
						this.dataLength = this.inventoryList.length;
						this.firstData = this.inventoryList[0] ? this.inventoryList[0].sessionNo : '无';
						
						// 多次强制更新确保渲染
						this.$forceUpdate();
						setTimeout(() => {
							this.$forceUpdate();
						}, 50);
						setTimeout(() => {
							this.$forceUpdate();
						}, 200);
					} else {
						this.$set(this, 'inventoryList', []);
						this.dataLength = 0;
						this.firstData = '无';
						console.log('没有数据，设置为空数组');
					}
				} catch (error) {
					console.error('加载数据失败:', error);
					this.$set(this, 'inventoryList', []);
					this.dataLength = 0;
					this.firstData = '无';
					this.apiStatus = '加载失败';
					this.apiResponse = { error: error.message || '未知错误' };
					uni.showToast({
						title: '加载失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
				}
			},

			// 执行盘点
			async executeInventory(item, index) {
				console.log('执行盘点，item:', item, 'index:', index);
				console.log('当前inventoryList:', this.inventoryList);
				
				// 如果item为空，尝试从inventoryList中获取
				if (!item && index !== undefined && this.inventoryList[index]) {
					item = this.inventoryList[index];
					console.log('从列表获取item:', item);
				}
				
				// 如果还是没有item，尝试通过sessionNo查找
				if (!item && this.inventoryList.length > 0) {
					// 使用最后一个item作为默认值
					item = this.inventoryList[this.inventoryList.length - 1];
					console.log('使用默认item:', item);
				}
				
				if (!item || !item.sessionNo) {
					console.error('item或sessionNo为空，无法执行盘点', item);
					uni.showToast({
						title: '数据异常，无法执行盘点',
						icon: 'none'
					});
					return;
				}
				
				// 跳转到执行盘点页面
				console.log('跳转到执行盘点页面，sessionNo:', item.sessionNo);
				uni.navigateTo({
					url: `/pages/spare-parts/inventory-execute?sessionNo=${item.sessionNo}`
				}).catch(error => {
					console.error('跳转失败:', error);
					uni.showToast({
						title: '跳转失败',
						icon: 'none'
					});
				});
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 跳转到新增盘点单
			goAdd() {
				uni.navigateTo({
					url: '/pages/spare-parts/inventory-add'
				});
			},
			
			// 搜索输入
			onSearchInput() {
				// 简单的搜索功能
				this.loadData();
			},
			
			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
				this.loadData();
			},
			
			// 查看详情
			viewDetail(item, index) {
				console.log('查看详情，item:', item, 'index:', index);
				
				// 如果item为空，尝试从inventoryList中获取
				if (!item && index !== undefined && this.inventoryList[index]) {
					item = this.inventoryList[index];
					console.log('从列表获取item:', item);
				}
				
				if (!item || !item.id) {
					console.error('item或id为空:', item);
					uni.showToast({
						title: '数据异常，无法查看详情',
						icon: 'none'
					});
					return;
				}
				
				console.log('跳转到详情页面，id:', item.id);
				uni.navigateTo({
					url: `/pages/spare-parts/inventory-detail?id=${item.id}`
				});
			},
			
			// 长按显示操作菜单
			showItemActions(item) {
				uni.showActionSheet({
					itemList: ['编辑', '删除'],
					success: (res) => {
						if (res.tapIndex === 0) {
							// 编辑
							this.editInventory(item);
						} else if (res.tapIndex === 1) {
							// 删除
							this.deleteInventory(item);
						}
					}
				});
			},
			
			// 编辑盘点单
			editInventory(item) {
				uni.navigateTo({
					url: `/pages/spare-parts/inventory-edit?id=${item.id}`
				});
			},
			
			// 删除盘点单
			async deleteInventory(item) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除盘点单"${item.sessionNo}"吗？删除后无法恢复。`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '删除中...' });
								const result = await delInventory(item.id);
								uni.hideLoading();
								
								if (result && result.code === 200) {
									uni.showToast({ title: '删除成功', icon: 'success' });
									// 刷新列表
									this.loadData();
								} else {
									uni.showToast({ title: result.msg || '删除失败', icon: 'none' });
								}
							} catch (e) {
								uni.hideLoading();
								console.error('删除盘点单失败:', e);
								uni.showToast({ title: '删除失败: ' + (e.message || '未知错误'), icon: 'none' });
							}
						}
					}
				});
			},
			
			// 获取状态文本
			getStatusText(status) {
				return this.statusMapping[status] || status || '-';
			},
			
			// 获取状态样式类
			getStatusClass(status) {
				const statusClassMap = {
					'PENDING': 'status-pending',
					'IN_PROGRESS': 'status-progress',
					'COMPLETED': 'status-completed',
					'CANCELLED': 'status-cancelled'
				};
				return statusClassMap[status] || 'status-pending';
			},
			
		// 获取仓库名称
		getWarehouseName(code) {
			return this.warehouseMapping[code] || code || '-';
		},
		
		// 获取状态名称
		getStatusName(status) {
			return this.statusMapping[status] || status || '未知';
		},
			
			// 格式化日期 - 兼容iOS
			formatDate(dateStr) {
				if (!dateStr) return '-';
				try {
					// 将日期字符串转换为iOS兼容格式
					let formattedDateStr = dateStr;
					if (dateStr.includes(' ')) {
						// 将 "2025-10-16 10:17:16" 转换为 "2025-10-16T10:17:16"
						formattedDateStr = dateStr.replace(' ', 'T');
					}
					const date = new Date(formattedDateStr);
					
					// 检查日期是否有效
					if (isNaN(date.getTime())) {
						return dateStr; // 如果解析失败，返回原始字符串
					}
					
					return date.toLocaleDateString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit'
					}) + ' ' + date.toLocaleTimeString('zh-CN', {
						hour: '2-digit',
						minute: '2-digit'
					});
				} catch (error) {
					console.error('日期格式化错误:', error);
					return dateStr;
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background: #F5F5F5;
	}

	.header-actions {
		display: flex;
		gap: 15rpx;
	}

	.action-btn {
		width: 70rpx;
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(255, 255, 255, 0.3);
		border-radius: 50%;
		transition: all 0.2s;
		
		&:active {
			background: rgba(255, 255, 255, 0.5);
			transform: scale(0.95);
		}
	}

	.btn-icon {
		font-size: 70rpx;
		color: black;
		font-weight: bold;
	}

	/* 搜索栏 */
	.search-section {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background: white;
	}

	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		background: #F5F5F5;
		border-radius: 50rpx;
		padding: 0 30rpx;
		height: 80rpx;
	}

	.search-icon {
		font-size: 32rpx;
		margin-right: 20rpx;
		color: #999;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		height: 80rpx;
		line-height: 80rpx;
	}

	.clear-icon {
		font-size: 32rpx;
		color: #999;
		padding: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 盘点单卡片列表 */
	.inventory-list {
		padding: 0 30rpx 30rpx;
	}

	.inventory-card {
		display: flex;
		background: white;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		transition: transform 0.2s;
		
		&:active {
			transform: scale(0.98);
		}
	}

	/* 卡片内容 */
	.card-content {
		flex: 1;
		padding: 24rpx 30rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.status-badge {
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
		font-weight: 500;
		white-space: nowrap;
		margin-left: 12rpx;
	}

	.status-badge.pending {
		background-color: #FFF3E0;
		color: #FF9800;
	}

	.status-badge.completed {
		background-color: #E8F5E9;
		color: #4CAF50;
	}

	.card-info {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.info-row {
		display: flex;
		align-items: center;
		font-size: 26rpx;
	}

	.info-label {
		color: #999;
		min-width: 140rpx;
	}

	.info-value {
		color: #666;
		flex: 1;
	}

	.title-text {
		font-size: 18px;
		font-weight: bold;
		color: #333;
	}

	/* 详情行 */
	.item-details {
		margin-bottom: 15px;
	}

	.detail-row {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.detail-label {
		font-size: 14px;
		color: #666;
		width: 80px;
		flex-shrink: 0;
	}

	.detail-value {
		font-size: 14px;
		color: #333;
		flex: 1;
	}

	/* 操作按钮 */
	.item-actions {
		display: flex;
		justify-content: flex-end;
		margin-top: 10px;
	}

	.execute-btn {
		background-color: #007bff;
		color: white;
		border: none;
		border-radius: 6px;
		padding: 10px 20px;
		font-size: 14px;
		font-weight: 500;
		cursor: pointer;
		transition: background-color 0.2s;
	}

	.execute-btn:active {
		background-color: #0056b3;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 20px;
	}

	.empty-icon {
		font-size: 48px;
		margin-bottom: 15px;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 16px;
		color: #999;
	}
</style>